<template>
    <div class="switch" @click="handlerCreate"> + 手动添加新闻 </div>

    <el-drawer v-model="drawer" title="手动添加新闻" :direction="direction" :before-close="handleClose" size="60%" @closed="handleDrawerClosed">
        <news-editt-from :mode="mode" :selectNews="currentNews" @close="drawer = false"></news-editt-from>
    </el-drawer>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import type { DrawerProps } from 'element-plus'
import { ElMessageBox } from 'element-plus'
import NewsEdittFrom from '@/page/NewsEdittFrom.vue'

const drawer = ref(false)
const currentNews = ref(null) // 存储当前选中的新闻

const props = defineProps({
    selectNews: Object
})

const direction = ref<DrawerProps['direction']>('rtl')
const mode = ref<'create' | 'read' | 'edit'>('create')
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('确定关闭吗？')
    .then(() => {
      // 重置状态
      drawer.value = false
      mode.value = 'create'
      currentNews.value = null // 清空当前新闻数据
      done()
    })
    .catch(() => {
      // catch error
    })
}
const handlerCreate = () => {
    mode.value = 'create'
    currentNews.value = null // 确保在create模式下currentNews为null
    drawer.value = true
}

// 处理抽屉完全关闭后的回调
const handleDrawerClosed = () => {
  // 重置状态
  mode.value = 'create'
  currentNews.value = null // 清空当前新闻数据
}

// 处理新闻点击的方法
const handleNewsClick = (newsData: any) => {
    if (newsData) {
        currentNews.value = newsData // 存储新闻数据
        mode.value = 'read' // 设置mode为read
        drawer.value = true
    }
}

// 暴露方法给父组件
defineExpose({
    handleNewsClick
})
</script>

<style>
.switch {
    width: 100%;
    padding: 20px 0;
    line-height: 40px;
    text-align: center;
    border: 1px dashed #ccc;
    border-radius: 5px;
}
</style>